package com.spider.gp.processor;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spider.gp.dao.*;
import com.spider.gp.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * description:
 *
 * @author clare
 * @date 2022/05/20 08:56
 **/
@Component
public class GpDetailProcessor implements PageProcessor {
    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000);


    @Autowired
    private GpInfoDao gpInfoDao;
    @Autowired
    private GpDetailDao gpDetailDao;

    @Override
    public void process(Page page) {
//        String reportTime = formatter.format(new Date());
//        String reportTime = "2022-08-01";

        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String reportTime = formatter.format(new Date());

        String url = page.getUrl().get();
        List<String> all = page.getJson().jsonPath("$.data.klines").all();
        if (all == null || all.size() == 0) {
            return;
        }
        String code = page.getJson().jsonPath("$.data.code").get();

        LambdaQueryWrapper<GpInfo> wrapper01 = new LambdaQueryWrapper<>();
        wrapper01.eq(GpInfo::getCode,code);
        GpInfo gpInfo = gpInfoDao.selectOne(wrapper01);

        if (url.contains("secid=1.000001")){
            code = "1000001";
            gpInfo = GpInfo.builder().code("1000001").shortName("上证指数").build();
        }
        if (url.contains("secid=0.399001")){
            code = "0399001";
            gpInfo = GpInfo.builder().code("0399001").shortName("深证指数").build();
        }
        LambdaQueryWrapper<GpDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GpDetail::getCode,code);
        GpDetail gpDetail = gpDetailDao.selectOne(wrapper);
        StringBuffer str = new StringBuffer();

        //获取时间以及收盘价 数组
        if (gpDetail != null){
            String detail = gpDetail.getDetail();
            str.append(detail);
        }
        all.forEach(e -> {
            str.append(e).append(";");
        });



        if (gpDetail == null){
            //第一次新增
            gpDetailDao.insert(GpDetail.builder().reportTime(reportTime).code(code).name(gpInfo.getShortName()).detail(String.valueOf(str)).build());
        }else {
            gpDetailDao.updateById(GpDetail.builder().reportTime(reportTime).code(code).name(gpInfo.getShortName()).detail(String.valueOf(str)).build());
        }


    }

    @Override
    public Site getSite() {
        return site;
    }
}








